import json

import yaml
import requests
from typing import Any, Dict

from app.schemas.generate import LLMRequestPayload


class HTTPLLMClient:
    def __init__(self, config_path: str = "D:/code/AI_live_master/app/core/config.yaml"):
        self.config = self._load_config(config_path)
        self.api_url = self.config["llm"]["api_url"]
        self.auth_key = self.config["llm"]["auth_key"]
        self.auth_secret = self.config["llm"]["auth_secret"]
        self.token = f"Bearer {self.auth_key}.{self.auth_secret}"

    def _load_config(self, path: str) -> Dict[str, Any]:
        with open(path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)

    def post(self, payload: LLMRequestPayload) -> Dict[str, Any]:
        headers = {
            "Content-Type": "application/json",
            "Authorization": self.token
        }
        response = requests.post(self.api_url, json=payload.dict(), headers=headers)
        response.raise_for_status()
        response_data =response.json()
        try:
            content = response_data.get("choices", [{}])[0].get("content", "")
            return content
        except (IndexError, KeyError):
            raise ValueError("未能从响应中提取到有效的 content 字段")
